package com.yuexiao.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuexiao.config.RedisUtil;
import com.yuexiao.pojo.Category;
import com.yuexiao.pojo.Setmeal;
import com.yuexiao.pojo.SetmealDish;
import com.yuexiao.service.CategoryService;
import com.yuexiao.service.DishService;
import com.yuexiao.service.SetmealDishService;
import com.yuexiao.service.SetmealService;
import com.yuexiao.mapper.SetmealMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.security.PrivateKey;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @description 针对表【setmeal(套餐)】的数据库操作Service实现
 * @createDate 2022-08-10 14:10:57
 */
@Component
@Service(interfaceClass = SetmealService.class)
@Transactional(rollbackFor = Exception.class)
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal>
        implements SetmealService {

    @Resource
    private RedisUtil redisUtil;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 根据条件分页查询套餐数据
     *
     * @param page     int 当前页
     * @param pageSize int 每页显示条数
     * @param name     String 查询条件套餐名
     * @return Page mybatisplus自带的分页对象
     */
    @Override
    public Page getSetmealPage(int page, int pageSize, String name) {

        //先从redis中查询是否有套餐数据，如果有则直接返回数据
        Page setmeals = (Page) redisUtil.hget("setmeal", page + "_" + pageSize + "_" + name);
        if (setmeals != null && setmeals.getTotal() > 0) {
            return setmeals;
        }

        //从数据库中查询数据
        Page<Setmeal> setmealPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //判断查询条件是否为空，不为空则拼装查询条件
        if (name != null && !"".equals(name) && !"null".equals(name)) {
            setmealLambdaQueryWrapper.like(Setmeal::getName, name);
        }

        Page<Setmeal> selectPageResult = baseMapper.selectPage(setmealPage, setmealLambdaQueryWrapper);
        //取出List数据
        List<Setmeal> records = selectPageResult.getRecords();
        records = records.stream().map((item) -> {
            //根据分类id查询分类数据
            item.setCategory(categoryService.getById(item.getCategoryId()));
            return item;
        }).collect(Collectors.toList());
        //重新封装回page
        selectPageResult.setRecords(records);

        //判断查询条件为空的情况下且数据查询数据不为空的情况下再进行redis存储操作
        if (name == "" || Objects.isNull(name) || name == "null") {
            if (selectPageResult != null && selectPageResult.getTotal() > 0) {
                redisUtil.hset("setmeal", page + "_" + pageSize + "_" + name, selectPageResult);
            }
        }

        return selectPageResult;
    }


    /**
     * 新增套餐数据
     *
     * @param setmeal Setmeal 套餐实体类
     * @return boolean true or false
     */
    @Override
    public boolean insertSetmeal(Setmeal setmeal) {
        //新增套餐
        baseMapper.insert(setmeal);

        //取出菜品数据
        List<SetmealDish> setmealDishes = setmeal.getSetmealDishes();
        //将套餐id存入关联
        setmealDishes = setmealDishes.stream().map((item) -> {
            item.setSetmealId(String.valueOf(setmeal.getId()));
            return item;
        }).collect(Collectors.toList());
        setmealDishService.saveBatch(setmealDishes);

        //清除redis
        redisUtil.del("setmeal");
        redisUtil.del("setmealbycid");
        return true;
    }


    /**
     * 根据id查询套餐数据
     *
     * @param id Long 主键id
     * @return Setmeal 套餐对象
     */
    @Override
    public Setmeal getSetmealById(Long id) {
        //根据套餐id查询套餐数据
        Setmeal setmeal = baseMapper.selectById(id);
        if (setmeal != null) {
            //根据分类id查询分类数据
            Category categoryServiceById = categoryService.getById(setmeal.getCategoryId());
            setmeal.setCategory(categoryServiceById);

            //根据id查询套餐菜品关联表
            LambdaQueryWrapper<SetmealDish> setmealDishLambdaQueryWrapper = new LambdaQueryWrapper<>();
            setmealDishLambdaQueryWrapper.eq(SetmealDish::getSetmealId, setmeal.getId());
            List<SetmealDish> setmealDishList = setmealDishService.list(setmealDishLambdaQueryWrapper);
            setmeal.setSetmealDishes(setmealDishList);
        }

        return setmeal;
    }


    /**
     * 更新套餐信息
     *
     * @param setmeal Setmeal 套餐对象
     * @return boolean true or false
     */
    @Override
    public boolean updateSetmeal(Setmeal setmeal) {

        //更新套餐数据
        baseMapper.updateById(setmeal);

        //根据套餐id删除套餐菜品关联表中的数据
        LambdaQueryWrapper<SetmealDish> setmealDishQueryWrapper = new LambdaQueryWrapper<>();
        setmealDishQueryWrapper.eq(SetmealDish::getSetmealId, setmeal.getId());
        setmealDishService.remove(setmealDishQueryWrapper);

        //插入新的关联
        List<SetmealDish> setmealDishes = setmeal.getSetmealDishes();
        setmealDishes = setmealDishes.stream().map((item) -> {
            item.setSetmealId(String.valueOf(setmeal.getId()));
            return item;
        }).collect(Collectors.toList());
        setmealDishService.saveBatch(setmealDishes);

        //清除redis
        redisUtil.del("setmeal");
        redisUtil.del("setmealbycid");
        return true;
    }

    /**
     * 根据id数组更改套餐状态
     *
     * @param status int 状态
     * @param ids    Long[] id数组
     * @return boolean true or false
     */
    @Override
    public boolean updateStatusByIds(int status, Long[] ids) {

        for (Long id : ids) {
            Setmeal setmeal = new Setmeal();
            setmeal.setId(id);
            setmeal.setStatus(status);
            baseMapper.updateById(setmeal);
        }

        //清除redis
        redisUtil.del("setmeal");
        redisUtil.del("setmealbycid");
        return true;
    }

    @Override
    public boolean deleteSetmeal(Long[] ids) {

        //删除套餐数据
        baseMapper.deleteBatchIds(Arrays.asList(ids));

        //根据id删除套餐和菜品关联表中的数据
        LambdaQueryWrapper<SetmealDish> setmealDishQueryWrapper = new LambdaQueryWrapper<>();
        setmealDishQueryWrapper.in(SetmealDish::getSetmealId, ids);
        setmealDishService.remove(setmealDishQueryWrapper);

        //清除redis
        redisUtil.del("setmeal");
        redisUtil.del("setmealbycid");
        return false;
    }

    /**
     * 根据分类id查询已经上架的套餐
     *
     * @param cid    Long 分类id
     * @param status int 上架状态
     * @return List<Setmeal> 套餐对象结合
     */
    @Override
    public List<Setmeal> getSetmealListByCid(Long cid, int status) {

        //先从redis中获取，如果获取到直接返回
        Object setmealbycid = redisUtil.hget("setmealbycid", String.valueOf(cid));
        if (setmealbycid != null) {
            return (List<Setmeal>) setmealbycid;
        }

        //从数据库中获取
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Setmeal::getCategoryId, cid);
        queryWrapper.eq(Setmeal::getStatus, status);
        List<Setmeal> setmeals = baseMapper.selectList(queryWrapper);
        //存入redis
        redisUtil.hset("setmealbycid", String.valueOf(cid), setmeals);
        return setmeals;
    }
}




